package pers.ree.demo.concurrent.lock;

import java.util.concurrent.locks.LockSupport;

public class LockSupportDemo {

    public static Object u = new Object();
    static ChangeObjectThread t1 = new ChangeObjectThread("t1");
    static ChangeObjectThread t2 = new ChangeObjectThread("t2");

    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(String name) {
            super(name);
        }
        @Override public void run() {
            synchronized (u) {
                System.out.println("in " + getName());
//                try {
//                    Thread.sleep(3000L);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                System.out.println(getName() + " after sleep");
                LockSupport.park(); // unpark或者interrupt都会结束park，使代码继续往下执行
                System.out.println(getName() + " after park");
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(getName() + "被中断了，isInterrupted=" + Thread.currentThread().isInterrupted());
                }
                System.out.println(getName() + "继续执行");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        t1.start();
//        LockSupport.unpark(t1); // 如果unpark在park前调用，则park不会起到停止线程执行的效果
        Thread.sleep(1000L);Thread.yield();
        System.out.println("before t2 start");
        t2.start();
        System.out.println("after t2 start");
        Thread.sleep(3000L);
        System.out.println("before t1 interrupt");
        t1.interrupt();
        LockSupport.unpark(t2); // 这一句只要在t2 start之后就可以
        System.out.println("after t2 unpark");
        // t1.join、t2.join主要只是让主线程等待t1,t2执行完，再继续，即使没有这两句，也不影响t1,t2执行效果
        t1.join();
        System.out.println("after t1 join");
        t2.join();
        System.out.println("main end");
    }
}
